 <template>
<div>
  
    <van-nav-bar title="login" class="page-nav-bar" @click="this.$router.back()"> 
    <template #left>
      <van-icon name="cross" size="18" />
    </template>
    </van-nav-bar> 
<van-form @submit="onSubmit">
    <van-field name="userName" placeholder="Please enter the username" left-icon="manager" v-model="userName" :rules="userFormRules.userName"/>
    <van-field type="password" name="userPWd" placeholder="Continue enter your password" left-icon="eye" v-model="userPwd" :rules="userFormRules.userPwd "/>
    <div style="margin: 16px;">
    <van-button round block type="primary" native-type="submit">
      登录
    </van-button>
    </div>  
</van-form>
</div>
</template>
<script >
import {reactive,toRefs} from 'vue';
import {login} from '../../api/user';
import {Toast} from 'vant';
import {useStore} from 'vuex'
import store from '../../store';
import router from '../../router'
//构建登录请求
//获取用户名和密码发送到服务端
function userSubmit(user){
  const store = useStore();
  const onSubmit = async () => {
    Toast.loading({
    message: '加载中...',
    forbidClick: true,
  });
    const res = await login(user)
    if(res.data.code === 0){
      store.commit('setUser',res.data);
      //console.log('User logined in successfully')
      Toast.success('User logined in successfully');
      router.push("/my");
    }else{
      //console.log('Wrong user name or password')
      Toast.fail('Wrong user name or password');
    }
  };

  //定义表单校验规则
  const userFormRules = {
    userName:[{require:true,message:"Please enter your userName"}],
    userPwd:[{require:true,message:"Please enter your userPwd"},{pattern:/\d{6}$/,message:"Wrong passwprd format"}]
  }

  return {
    onSubmit,
    userFormRules
  };
}
export default{
  setup(){
    const user = reactive({
      userName:'',
      userPwd:'',
    });
    return {
      ...toRefs(user),
      ...userSubmit(user)
    }
  }
};
</script>
<style></style>